<template>
  <div class="common-layout">
    <el-container class="listVenues">
      <el-header style="padding:0px">
        <Header>场管列表</Header>
      </el-header>
      <el-main>
        <el-main class="main">
          <el-row :gutter="20">
            <el-col :span="4" :offset="1">
              <el-input
                v-model="input2"
                class="w-50 m-2"
                placeholder="请输入关键字"
                :suffix-icon="Search"
                @input="search"
              />
            </el-col>
            <el-col :span="1">
              <el-button type="primary" plain @click="searchValue"
                >查询</el-button
              >
            </el-col>
            <el-col :span="2" :offset="9">
              <el-button type="info" @click="add">增加场馆</el-button>
            </el-col>
            <el-col :span="3" style="text-align: center">
              <el-button type="danger" plain @click="toggleSelection()"
                >批量删除</el-button
              >
            </el-col>
            <el-col :span="2">
              <el-button type="primary" plain @click="show()"
                >导出数据</el-button
              >
            </el-col>
          </el-row>
          <el-main>
            <el-table
              :data="state.tableData"
              style="width: 100%"
              stripe
              ref="multipleTableRef"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="场馆名称" width="180" align="center">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <span style="margin-left: 10px">{{ scope.row.name }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="联系电话" width="180" align="center">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <el-icon><Iphone /></el-icon>
                    <span style="margin-left: 10px">{{ scope.row.phone }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="场馆地址" width="180" align="center">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <span style="margin-left: 10px">{{
                      scope.row.address
                    }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="邮箱" width="180" align="center">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <span style="margin-left: 10px">{{ scope.row.email }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="状态" width="180" align="center">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <span
                      style="margin-left: 10px; color: #2e8b57"
                      v-if="scope.row.status === '可预约'"
                    >
                      可预约</span
                    >
                    <span style="margin-left: 10px; color: #dcdcdc" v-else>
                      已预约</span
                    >
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="180">
                <template #default="scope">
                  <el-button
                    size="small"
                    @click="handleEdit(scope.$index, scope.row)"
                    >编辑</el-button
                  >
                  <el-button
                    size="small"
                    type="danger"
                    @click="handleDelete(scope.$index, scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-main>
          <el-row :gutter="20">
            <el-col :offset="19" span="9">
              <el-pagination
                small
                background
                :page-size="state.pageSize"
                layout="prev, pager, next"
                :total="state.total"
                class="mt-4"
                @current-change="handleCurrentChange"
              />
            </el-col>
          </el-row>
        </el-main>
      </el-main>
    </el-container>

    <el-dialog v-model="dialogTableVisible" title="表格导出">
      <el-table :data="state.Excel" stripe>
        <el-table-column
          property="name"
          label="场馆名称"
          width="150"
          align="center"
        />
        <el-table-column
          property="phone"
          label="电话号码"
          width="150"
          align="center"
        />
        <el-table-column
          property="address"
          label="场馆地址"
          width="100"
          align="center"
        />
        <el-table-column
          property="email"
          label="邮箱地址"
          width="200"
          align="center"
        />
        <el-table-column
          property="status"
          label="场馆状态"
          width="100"
          align="center"
        />
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogTableVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="(dialogTableVisible = false), confirm()"
          >
            确认导出
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, defineEmits } from "vue";
import { ElMessage, ElMessageBox, ElTable } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
// import useStore from "../store/ljh/index";
import * as XLSX from "xlsx";
import Header from "../components/zch/HeaderView.vue";
import { ListVenues, deleteVenues } from "../http/api";
import mitts from "../components/ljh/mitt";

// const store = useStore();
const input2 = ref("");
const value = ref("");
const router = useRouter();

const dialogTableVisible = ref(false);
// const options = [
//   {
//     value: "全部",
//     label: "全部",
//   },
//   {
//     value: "可预约",
//     label: "可预约",
//   },
//   {
//     value: "已预约",
//     label: "已预约",
//   },
//   {
//     value: "已禁用",
//     label: "已禁用",
//   },
// ];
let state = reactive({
  Excel: [],
  tableData: [],
  pageSize: 7,
  page: 1,
  total: 0,
});

//分页
const begin = () => {
  ListVenues({ limit: state.pageSize, page: state.page }).then((res :any) => {
    if (res.code == 0) {
      state.tableData = res.data;
    }
  });
};
const total = () => {
  ListVenues({}).then((res:any) => {
    console.log(res);
    if (res.code == 0) {
      state.total = res.data.count;
    }
  });
};
onMounted(() => {
  begin();
  total();
});

// 批量删除
const toggleSelection = () => {
  console.log(state.Excel);
  if (state.Excel == "") {
    ElMessage({
      type: "warning",
      message: "请先选择数据",
      duration: 1000,
    });
  } else {
    ElMessageBox.confirm("数据一旦删除将不可恢复！", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        state.Excel.forEach((el) => {
          deleteVenues({ id: el.id }).then((res) => {
            console.log(res);
          });
          begin();
          total();
        });
        ElMessage({
          type: "success",
          message: "删除成功",
          duration: 1000,
        });
        // total();
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消删除",
        });
      });
  }
};
// input搜索框
const search = () => {
  console.log(input2);
  if (input2.value == "") {
    begin();
  }
};
const searchValue = () => {
  console.log(input2.value);
  ListVenues({ name: input2.value }).then((res) => {
    if (res.code == 0) {
      state.tableData = res.data;
    }
  });
};
// 新增跳转
function add() {
  // mitts.emit("msg", msg.value);
  // router.push({ path: "addVenue" });
  router.push({ path: "addVenue", query: { msg: "新增" } });
}
// 编辑跳转
const handleEdit = (scope: any, row: any) => {
  router.push({ path: "addVenue", query: { id: row.id, msg: "编辑" } });
};
// 删除操作
const handleDelete = (scope: any, row: any) => {
  ElMessageBox.confirm("数据一旦删除将不可恢复！", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteVenues({ id: row.id }).then((res) => {
        if (res.data.code == 0) {
          ElMessage({
            type: "success",
            message: "删除成功",
            duration: 1000,
          });
          begin();
          total();
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

const show = () => {
  if (state.Excel == "") {
    ElMessage({
      type: "warning",
      message: "请选择导出数据",
      duration: 1000,
    });
  } else {
    dialogTableVisible.value = true;
  }
};
// 导出表格
const confirm = () => {
  // const head = reactive({
  //   id: "编号",
  //   name: "场馆名称",
  //   tel: "电话号码",
  //   address: "地址",
  //   time: "建成日期",
  //   specificAddress: "具体地址",
  //   email: "邮箱",
  //   state: "状态",
  //   des: "场馆描述",
  // });
  // exportExcel(tableData.value, "test", titleArr, "sheetName");
  // 创建工作表
  const data = XLSX.utils.json_to_sheet(state.Excel);
  // 创建工作簿
  const wb = XLSX.utils.book_new();
  // 将工作表放入工作簿中
  XLSX.utils.book_append_sheet(wb, data, "data");
  // 生成文件并下载
  XLSX.writeFile(wb, "场馆表格.xlsx");
};
// 多选选中值
const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  state.Excel = [];
  multipleSelection.value = val;
  multipleSelection.value.forEach((el) => {
    state.Excel.push(el);
  });
  return state.Excel;
};

// 当前页切换
const handleCurrentChange = (val) => {
  state.page = val;
  begin();
};

// 下拉框搜索
// const searchValue = () => {
//   console.log(value);
// };

// 搜索框闭包
// function debounce(fn: { (): void; (): void }, delay: number | undefined) {
//   let timer: null | NodeJS.Timeout = null;
//   // 内部函数使用外部变量，闭包
//   return function () {
//     if (timer) {
//       clearTimeout(timer);
//     }
//     timer = setTimeout(() => {
//       fn();
//     }, delay);
//   };
// }
// const search = debounce(function () {
//   console.log(input2);
// }, 500);

// 节流
// let flag = true;
// window.onscroll = function () {
//   if (flag) {
//     setTimeout(() => {
//       console.log(111);
//       flag = true;
//     }, 500);
//   }
//   flag = false;
// };
</script>

<style scoped>
.listVenues {
  background-color: rgba(242, 242, 242, 1);
  border-radius: 30px;
  border-radius: 0 0 30px 30px;
  display: flex;
}
.main {
  background-color: white;
  border-radius: 20px;
}
</style>
